const axios = require("axios").default;
const mongoose = require("mongoose");
const productSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },
    descriptions: {
      type: String,
    },
    onSale: {
      type: Boolean,
      default: false,
    },
    content: {
      type: String,
      default: "",
    },
    quantity: {
      type: Number,
      default: 10,
    },
    price: {
      type: Number,
      default: 0.0,
    },
    coverImg: {
      type: String,
    },
    productCategory: {
      type: mongoose.SchemaTypes.ObjectId,
      ref: "ProductCategory",
    },
  },
  {
    timestamps: true,
  }
);

const Product = mongoose.model("Product", productSchema);

mongoose.connect("mongodb://localhost:27017/cake-shop").then((res) => {
  console.log(res);
  Product.find({})
    .sort({ _id: -1 })
    .then((res) => console.log(res));

  var products = [];
  axios
    .get(
      "https://www.duitang.com/napi/blog/list/by_filter_id/?include_fields=top_comments%2Cis_root%2Csource_link%2Citem%2Cbuyable%2Croot_id%2Cstatus%2Clike_count%2Csender%2Calbum%2Creply_count&filter_id=%E5%A4%B4%E5%83%8F&start=48&_=1595389274918",
      {}
    )
    .then((res) => {
      console.log(res.data.data["object_list"]);
      res.data.data["object_list"].forEach((p) => {
        var temP = {};
        temP.name = p.album.name;
        temP.descriptions = p.msg;
        temP.price = p.album.like_count * 1;
        temP.coverImg = p.album.covers[0];
        products.push(temP);
      });
      //   console.log(products);
      Product.insertMany(products);
      console.log("插入成功");
    });
});
